<template>
<div class="word-fream">



    <!-- 1.左侧tree -->
    <div class="word-tree" v-if="treeData.length">
        <el-tree :data="treeData" :props="defaultProps" :highlight-current=true ref="tree" @node-click="handleNodeClick"></el-tree>
    </div>


    <div class="rightDiv">
        <!-- 2.1.当前节点信息: 节点, 关键词列表 -->
        <div class="cur_nodeinfo">
            <div>关键词: </div>
            <div>
                <el-tag :key="key" v-for="(tag, key) in policy_words" closable :disable-transitions="false" @close="tagDel(key)"  @click="editClick(tag)">
                    {{tag.keyword}}
                </el-tag>
            </div>
        </div>
    </div>


    <el-dialog title="词表修改" :visible.sync="dialogFormVisible" width="30%">
      <el-form :model="form" size="small">
        <el-form-item label="词语" :label-width="formLabelWidth">
          <el-input v-model="form.keyword" auto-complete="off" :disabled="form.add" style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item label="所属框架" :label-width="formLabelWidth">
          <tree-select :options="wordsTree" placeholder="请选择分类..." :clearable="form.add"
                       v-model="form.wordFreamCurrentId"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialog_handleSubmit">确 定</el-button>
      </div>
    </el-dialog>


</div>
</template>


<script>
  import {getWordsTree,addTreeNodes,deleteTreeNodes} from '@/api/words-fream-tree'
  import {addWord, delWord, getWordsList} from "@/api/word-manage-list";
  import {addWords, deleteWords} from "@/api/stop-using";
  import TreeSelect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'


  let id = 1000;
  export default {
    name: 'TinymceDemo',
    components: { TreeSelect },
    data() {
      return {
        listLoading: false,
        treeData:[],
        defaultProps: {
          //children: 'childWordFream',
          children: 'children',
          label: 'name'
        },

        curNode:{ id:0, label:''  },
        policy_words:[],        // [{id:1, keyword:'xx', /*wordFreamId:curNodeId*/}]



        wordsTree: [],
        wordsTree_selected: [],

        dialogFormVisible: false,
        formLabelWidth: '120px',
        form: {
          id: '',
          keyword: '',
          wordFreamIds: [],
          wordFreamOldId: [],
          wordFreamCurrentId: [],
          add: false,
        },

      }
    },
    created() {
      this.getWordsTree();
    },
    methods: {
      getWordsTree() {
        this.listLoading = true;
        getWordsTree().then(res => {
          this.treeData = res.result;
          this.listLoading = false;

          this.wordsTree = res.result;      // 弹窗中用到的
        });
      },
      handleNodeClick(data) {
        console.log(data);
        this.curNode = data;        // id:2, label:"xxx", level:2
        this.getWordsList();
      },
      getWordsList(){
            this.policy_words = [];
            if( this.curNode.id ){
                let param = { wordFreamId: this.curNode.id, pageSize:100}
                getWordsList(param).then(res => {
                    console.log('[getWordsList]' , res.result.list);
                    // {id:1, keyword:'xx'}
                    this.policy_words = res.result.list;
                })
            }
      },
      tagDel(key){
            this.$confirm("确定删除?", {type: "warning"}).then(() => {
                let param={id: this.policy_words[key].id }
                delWord(param).then(res => {
                    console.log('[tagDel]res: ' ,res);
                    this.policy_words.splice(key, 1)
                    this.$message({ message: '删除成功！', type: 'success' })
                })
            }).catch(() => {})
      },

      append(data) {
        this.$prompt('子节点名称', '新增子节点', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /\S+/,
          inputErrorMessage: '名称不可为空'
        }).then(({value}) => {
          this.listLoading = false;
          let param = {
            name:value,
            parentId:data.id
          };
          addTreeNodes(param).then(res=>{
            this.getWordsTree();
            this.listLoading = false;
            this.$message({
              type: 'success',
              message: '新增成功'
            });
          }).catch(error => {
            this.listLoading = false;

          });
        }).catch(() => {})
      },

      remove(node, data) {
        this.$confirm("确定删除?", {type: "warning"}).then(() => {

            this.listLoading = true;
            deleteTreeNodes({id: data.id}).then(res => {
              this.getWordsTree();
              this.$message({
                message: "删除成功",
                type: "success"
              });
            }).catch(error => {
              this.listLoading = false;
            })
        }).catch(() => {})
      },

      edit(node, data){
        this.$prompt('新名称', '修改节点', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /\S+/,
          inputErrorMessage: '名称不可为空'
        }).then(({value}) => {
          this.listLoading = false;
          let param = {
            name:value,
            id:data.id,
            // 判断该节点是否有父节点，有的话传父节点id，没有传null，表示该节点为根节点
            parentId:typeof (node.parent.data)==="object"?node.parent.data.id:null
          };
          addTreeNodes(param).then(res=>{
            this.getWordsTree();
            this.listLoading = false;
            this.$message({
              type: 'success',
              message: '修改成功'
            });
          }).catch(error => {
            this.listLoading = false;

          });
        });
      },
      renderContent(h, { node, data, store }) {
        return (
          <span style="flex: 1; display: flex; align-items: center; justify-content: space-between; font-size: 14px; padding-right: 8px;">
          <span>
          <span>{node.label}</span>
          </span>
          <span>
          <el-button style="font-size: 12px;" type="text" on-click={ () => this.append(data) }><i class="el-icon-plus"></i></el-button>
        <el-button style="font-size: 12px;" type="text" on-click={ () => this.remove(node, data) }><i class="el-icon-delete"></i></el-button>
        <el-button style="font-size: 12px;" type="text" on-click={ () => this.edit(node, data) }><i class="el-icon-edit"></i></el-button>
        </span>
        </span>);
      },




      editClick(row) {
        // {id: 1791,keyword: "研发用地",wordFreamIteams:[] }
        console.log('[editClick]', row); //return;
        this.form.id = row.id;
        this.form.add = false;
        this.form.keyword = row.keyword;
        
        this.form.wordFreamIds = row.wordFreamIteams.map(val => {
            return val.wordFreamLeve4Id || val.wordFreamLeve3Id || val.wordFreamLeve2Id || val.wordFreamLeve1Id;
        });
        this.form.wordFreamCurrentId = this.curNode.id;
        this.form.wordFreamOldId = this.curNode.id;
        
        console.log('[editClick]', row);
        this.dialogFormVisible = true;
      },

      dialog_handleSubmit() {
        //console.log('[dialog_handleSubmit]', this.form);return;
        if (this.form.id) {
          this.listLoading = true;
          if (this.form.add) {
            // 新增
            if (this.form.wordFreamCurrentId){
              this.form.wordFreamIds.push(this.form.wordFreamCurrentId)
            }
          } else {
            // 编辑
            const index = this.form.wordFreamIds.indexOf(this.form.wordFreamOldId);
            this.form.wordFreamIds.splice(index, 1, this.form.wordFreamCurrentId); // 将新选的框架替换掉之前的框架传给后台
          }

            // 提交时的字段: id,add,keyword,wordFreamIds
          addWord(this.form).then(res => {
            this.dialogFormVisible = false
            this.getWordsList();
            this.$message({ type: 'success', message: '修改成功' });
          }).catch(error => {
            this.$message({ type: 'error', message: '修改失败' });
          })
        }
      },


    },

  }
</script>

<style lang="less" scoped>
.word-fream{
    display: flex;

    .word-tree{
        width: 30%;
        margin-left: 0;
        border: 1px solid gray;
        padding: 20px;
        border-radius: 5px;
    }

    .rightDiv{
        width: 65%;
        padding-left: 48px;

        .el-tag{
            margin-right:5px; margin-top:5px; cursor:pointer;
        }

        .cur_nodeinfo{
            margin-top:10px;
        }

    }



}
</style>

